<template>
  <div>
    <Modal :value="value" @on-visible-change="visibleChange"
           :draggable="!$config.mask"
           :mask="$config.mask"
           :mask-closable="!$config.mask" :width="1000" :closable="!status">
      <p slot="header">
        用户文件上传
      </p>
      <Form ref="form" :model="temp" :rules="rules" label-position="top">
        <Row :gutter="16">
          <Col span="20">
            <FormItem prop="fileName">
              <Input v-model="temp.fileName" :readonly="true" style="width: 100%;" :clearable="true"
                     @on-clear="handleClear">
              </Input>
            </FormItem>
          </Col>
          <Col span="4" style="text-align: center;">
            <Upload id="upload" action="" :before-upload="beforeUpload" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="width:100%;">
              <Button type="info" icon="md-attach" :disabled="status" style="width:100%;">选择文件...</Button>
            </Upload>
          </Col>

        </Row>
        <Row>
          <Col span="23">
            <Progress :percent="fileUploadPercent" :stroke-width="20" text-inside></Progress>
          </Col>
          <Col span="1" style="text-align: center;">
            <template v-if="!status">
              <Icon type="md-close" color="#c5c8ce" class="icon"></Icon>
            </template>
            <template v-else>
              <Tooltip content="取消附件上传" transfer>
                <Icon type="md-close" @click="handleCancelClick" style="cursor:pointer;" class="icon"></Icon>
              </Tooltip>
            </template>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button icon="md-close" @click="cancel" :disabled="status">取消</Button>
        <Button type="success" icon="md-cloud-upload" :disabled="file===null || check" @click="handleUpload"
                :loading="status">上传附件
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Util from '@/lib/util';
import Ajax from '@/lib/ajax';

@Component({
  components: {},
})
export default class UserFileUpload extends AbpBase {
  name: string = 'UserFileUpload';

  @Prop({type: Boolean, default: false}) value: boolean;
  @Prop({
    type: Object, default: () => {
    }
  }) modalData: any;

  file = null;
  temp:any={};
  status: boolean = false;
  fileUploadPercent: number = 0;
  cancelFileUpload: boolean = false;
  check:boolean=false;

  rules={
    fileName: [
      {
        validator: (rule, value, callback) => {
          if (!this.temp.fileName) {
            this.check = true;
            callback(new Error('请选择要上传的用户文件'));

          } else {
            this.check = false;
            callback();
          }
        },
        trigger: 'change',
      },
      {
        validator: async (rule, value, callback) => {
          const format = ['xls', 'xlsx'];
          const _file_format = this.temp.fileName.split('.').pop().toLocaleLowerCase();
          const checked = await format.some(item => item.toLocaleLowerCase() === _file_format);
          if (!checked) {
            this.check = true;
            callback(new Error('用户文件仅支持Excel格式'));

          } else {
            this.check = false;

          }
        },
        trigger: 'change',
      },
    ],
  };

  cancel() {
    this.$emit('input', false);
  }

  async visibleChange(value: boolean) {
    if (!value) {
      this.reset();
      this.$emit('input', value);
    }else{
      (this.$refs.form as any).resetFields();
    }
  }
  handleCancelClick() {
    this.cancelFileUpload = true;
    this.fileUploadPercent=0;
  }

  handleClear() {
    if (!this.status) {
      this.file = null;
    }
  }

  async handleUpload() {
    if(this.hasPermission("Pages.Files.Upload")) {
      this.status = true;
      const fileSize = this.file.size;
      const shardingSize = 2 * 1024 * 1024;
      const shardingCount = Math.ceil(fileSize / shardingSize);
      const fileToken = Util.guid();
      for (let i = 0; i < shardingCount; i++) {
        if (this.cancelFileUpload) {
          break;
        }
        let start = i * shardingSize, end = Math.min(fileSize, start + shardingSize);
        const formData = new FormData();
        formData.append('file', this.file.slice(start, end));
        window.abp.content_disposition = 'attachment; filename="' + encodeURI(this.file.name) + '"; fileToken="' + fileToken + '"';
        window.abp.content_range = 'bytes ' + start + '-' + end + '/' + fileSize;
        const response = await Ajax.post(this.$config.remoteServiceBaseUrl + '/api/Users/ImportFromExcel', formData);
        window.abp.content_disposition = '';
        window.abp.content_range = '';
        this.fileUploadPercent = Math.floor(((i + 1) / shardingCount) * 100);

      }
      if (!this.cancelFileUpload) {

      }
      this.$Message.success({
        background: true,
        content: '用户文件 ' + this.temp.fileName + ' 上传成功，用户正在导入，导入完成后系统会发出通知',
        duration: this.$config.duration,
      });
      this.$emit('input', false);
    }else{
      this.$Message.error({
        background: true,
        content: '上传失败，缺少文件上传权限',
        duration: this.$config.duration,
      });
    }
  }

  beforeUpload(file) {
    this.file = file;
    this.temp.fileName = file.name;
    this.fileUploadPercent = 0;
    return false;
  }

  reset(){
    this.temp.fileName='';
    this.file=null;
    this.fileUploadPercent=0;
    this.status = false;
    this.cancelFileUpload = false;
  }


}
</script>

<style lang="less" scoped>
#upload::v-deep .ivu-upload{
  width:100%;
}
.icon{
  margin-top:2px;
  font-size:20px;
}
</style>
